<template>
  <div style="height: 100%">
    <div style="float: right; padding-bottom: 10px">
      <a-button type="primary" @click="handleCreate">创建拓扑</a-button>
    </div>
    <div style="margin-top: 10px">
      <a-table
        :row-selection="rowSelection"
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        bordered
        size="small"
        :pagination="{ pageSize: 2 }"
        :row-key="(record) => record.id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'operation'">
            <template v-if="record.desc === 'auto create topo view'">
              <a disabled>编辑</a>
              <a-divider type="vertical" />
              <a disabled>删除</a>
            </template>
            <template v-else>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a style="color: red" @click="handleDelete(record)">删除</a>
            </template>
          </template>
          <template v-else-if="column.key === 'nodeSize'">
            <template v-if="record.desc === 'auto create topo view'">
              <span>{{ record.moduleSize }}</span>
            </template>
            <template v-else>
              <a @click="handleNode(record)"
                ><span>{{ record.moduleSize }}</span></a
              >
            </template>
          </template>
          <template v-else-if="column.key === 'ruleSize'">
            <template v-if="record.desc === 'auto create topo view'">
              <span>{{ record.ruleSize }}</span>
            </template>
            <template v-else>
              <a @click="handleRule(record)"
                ><span>{{ record.ruleSize }}</span></a
              >
            </template>
          </template>
        </template>
      </a-table>
    </div>
  </div>

  <div v-if="showCreate">
    <TopoCreateModal :visible="showCreate" @ok="onCreateOk" @cancel="onCreateCancel" />
  </div>

  <div v-if="showNode">
    <TopoNodeModal
      :visible="showNode"
      :topo-data="nodeData"
      @ok="onNodeOk"
      @cancel="onNodeCancel"
    />
  </div>

  <div v-if="showEdit">
    <TopoEditModal
      :visible="showEdit"
      :topo-data="editData"
      @ok="onEditOk"
      @cancel="onEditCancel"
    />
  </div>

  <div v-if="showDelete">
    <DeleteModal
      :visible="showDelete"
      title="删除拓扑"
      :data="deleteData"
      @ok="onDeleteOk"
      @cancel="onDeleteCancel"
    />
  </div>
</template>

<script lang="js">
  import { Divider, Table, message } from 'ant-design-vue';
  import { useRouter } from 'vue-router';
  import bus from 'vue3-eventbus';
  import DeleteModal from '../components/DeleteModal.vue';
  import TopoEditModal from './TopoEditModal.vue';
  import TopoNodeModal from './TopoNodeModal.vue';
  import TopoCreateModal from './TopoCreateModal.vue'
  import { createTopoView, deleteTopoView, editTopoView, getTopoViewList } from '/@/api/module/topoView';
  import { useModuleStoreWithOut } from "/@/store/modules/module";

  export default {
    components: {
      "a-table": Table,
      "a-divider": Divider,
      DeleteModal,
      TopoEditModal,
      TopoNodeModal,
      TopoCreateModal,
    },
    data() {
      return {
        store: useModuleStoreWithOut(),
        router: useRouter(),
        showCreate: false,
        showDelete: false,
        showEdit: false,
        showNode: false,
        deleteData: null,
        editData: null,
        nodeData: null,
        tableData: [],
        loading: true,
        rowSelection: {
          selectedRowKeys: [],
          onChange: this.onSelectChange,
          type: 'radio',
        },
        columns: [
          {
            title: 'ID',
            key: 'id',
            dataIndex: 'id',
            align: 'center',
          },
          {
            title: 'Name',
            key: 'name',
            dataIndex: 'name',
            align: 'center',
          },
          {
            title: 'Description',
            key: 'desc',
            dataIndex: 'desc',
            align: 'center',
          },
          {
            title: 'Create Time',
            key: 'createTime',
            dataIndex: 'createTime',
            align: 'center',
          },
          {
            title: 'Module',
            key: 'nodeSize',
            dataIndex: 'nodeSize',
            align: 'center',
          },
          {
            title: 'Rule',
            key: 'ruleSize',
            dataIndex: 'ruleSize',
            align: 'center',
          },
          {
            title: 'Operation',
            key: 'operation',
            dataIndex: 'operation',
            align: 'center',
          },
        ],
      }
    },
    watch: {
      'store.parent': {
        async handler() {
          await this.doRefresh()
        }
      }
    },
    async mounted() {
      await this.doRefresh()

      bus.on("createModule", async () => {
        console.log("received createModule event")
        await this.doRefresh()
      })

      bus.on("editModule", async () => {
        console.log("received editModule event")
        await this.doRefresh()
      })
    },
    methods: {
      async doRefresh() {
        await this.refreshTable()
        if (this.tableData && this.tableData.length > 0) {
          this.rowSelection.selectedRowKeys = []
          this.rowSelection.selectedRowKeys.push(this.tableData[0].id)
          bus.emit('updateGraph', this.tableData[0].id)
          console.log("emit updateGraph event, param:", this.tableData[0].id)
        } else {
          bus.emit('updateGraph', 0)
          console.log("emit updateGraph event, param:", 0)
        }
      },
      handleEdit(record) {
        this.showEdit = true
        this.editData = record
      },
      onEditOk(data) {
        this.showEdit = false
        editTopoView({
          id: data.id,
          desc: data.desc,
          name: data.name,
        }).then(() => {
          message.success("edit topo view success")
          this.refreshTable()
        }).catch(() => {
          message.error("edit topo view failed")
        })
      },
      onEditCancel() {
        this.showEdit = false
      },
      handleNode(record) {
        this.showNode = true
        this.nodeData = record
      },
      async onNodeOk(data) {
        this.showNode = false
        await this.refreshTable()
        if (data.id == this.rowSelection.selectedRowKeys[0]) {
          bus.emit('updateGraph', data.id)
        }
      },
      onNodeCancel() {
        this.showNode = false
      },
      handleRule(record) {
        console.log(record)
      },
      handleDelete: function(record) {
        this.deleteData = record
        this.showDelete = true
        console.log(record)
      },
      async refreshTable() {
        this.tableData = await getTopoViewList({ module: this.store.getParent.id })
        this.loading = false
      },
      onDeleteOk: function(data) {
        this.showDelete = false
        deleteTopoView({
          id: data.id
        }).then(async () => {
          this.refreshTable()
          message.success('delete topo view success');
        }).catch(() => {
          message.error('delete topo view failed');
        })
      },
      onDeleteCancel: function() {
        this.showDelete = false
      },
      onSelectChange: function(selectedRowKeys, selectedRows) {
        console.log('onSelectChange')
        this.rowSelection.selectedRowKeys = selectedRowKeys
        bus.emit('updateGraph', selectedRows[0].id)
        console.log('444')
      },
      handleCreate() {
        this.showCreate = true
      },
      onCreateOk(data) {
        this.showCreate = false
        createTopoView({
          moduleId: this.store.getParent.id,
          desc: data.desc,
          name: data.name,
        }).then(() => {
          message.success("create topo view success")
          this.refreshTable()
        }).catch(() => {
          message.error("create topo view failed")
        })
      },
      onCreateCancel() {
        this.showCreate = false
      },
    },
  }
</script>
